package cn.px.service.sb.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.px.common.util.*;
import cn.px.dao.dto.store.SpareStoreDTO;
import cn.px.dao.entity.sb.SbInfo;
import cn.px.dao.entity.sb.SbModel;
import cn.px.dao.enums.*;
import cn.px.dao.mapper.purchase.PurchaseDispatchOrderMapper;
import cn.px.dao.mapper.purchase.PurchaseOrderMapper;
import com.github.pagehelper.PageHelper;
import cn.px.common.bean.AbstractPageResultBean;
import cn.px.common.enums.DataFilterTypeEnum;
import cn.px.common.exception.BusinessException;
import cn.px.dao.util.MessageTemplateUtil;
import cn.px.dao.util.UserUtil;
import cn.px.dao.vo.SysUserVO;
import cn.px.service.business.PurchaseBusinessService;
import cn.px.common.model.UserInfo;
import cn.px.dao.bean.MyPage;
import cn.px.dao.dto.sb.SbCheckDetailDTO;
import cn.px.dao.dto.sb.SbCheckFormDTO;
import cn.px.dao.dto.sb.SbInfoDTO;
import cn.px.dao.dto.upms.SysDeptDTO;
import cn.px.dao.entity.purchase.PurchaseDispatchOrder;
import cn.px.dao.entity.purchase.PurchaseDispatchOrderList;
import cn.px.dao.entity.purchase.PurchaseList;
import cn.px.dao.entity.purchase.PurchaseOrder;
import cn.px.dao.entity.sb.SbCheckDetail;
import cn.px.dao.entity.sb.SbCheckForm;
import cn.px.dao.entity.store.Store;
import cn.px.dao.mapper.sb.SbCheckDetailMapper;
import cn.px.dao.mapper.sb.SbCheckFormMapper;
import cn.px.dao.mapper.purchase.PurchaseDispatchOrderListMapper;
import cn.px.dao.mapper.purchase.PurchaseListMapper;
import cn.px.dao.mapper.sb.SbModelMapper;
import cn.px.dao.mapper.store.SpareStoreMapper;
import cn.px.dao.vo.query.sb.SbCheckFormVO;
import cn.px.dao.vo.query.store.StoreVO;
import cn.px.dao.vo.query.upms.SysDeptVO;
import cn.px.service.base.impl.BaseServiceImpl;
import cn.px.service.event.WorkplaceBacklogEvent;
import cn.px.service.purchase.PurchaseDispatchOrderListService;
import cn.px.service.purchase.PurchaseListService;
import cn.px.service.sb.SbCheckFormService;
import cn.px.service.sb.SbInfoService;
import cn.px.service.store.InStoreFormService;
import cn.px.service.store.SpareStoreService;
import cn.px.service.store.StoreService;
import cn.px.service.upms.SysDeptService;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 验收登记表 service 实现类
 * @author 品讯科技
 * @date 2024-08
 * @Version Copyright (c) 2020,北京乾元坤和科技有限公司 All rights reserved.
 */
@AllArgsConstructor
@Service("sbCheckFormService")
public class SbCheckFormServiceImpl extends BaseServiceImpl<SbCheckFormMapper, SbCheckForm, SbCheckFormDTO> implements SbCheckFormService {
    private SbCheckDetailMapper detailMapper;
    private SpareStoreMapper spareStoreMapper;
    private SpareStoreService spareStoreService;
    private StoreService storeService;
    private PurchaseDispatchOrderMapper purchaseDispatchOrderMapper;
    private PurchaseOrderMapper purchaseOrderMapper;
    private PurchaseListService purchaseListService;
    private PurchaseDispatchOrderListService purchaseDispatchOrderListService;
    private SbModelMapper sbModelMapper;
    private SbInfoService sbInfoService;
    private SysDeptService sysDeptService;
    private final PurchaseBusinessService purchaseBusinessService;
    private PurchaseListMapper purchaseListMapper;
    private PurchaseDispatchOrderListMapper purchaseDispatchOrderListMapper;

    private InStoreFormService inStoreFormService;

    @Override
    public int batchDelete(List<String> ids) {
        //Weekend<OutStoreForm> weekend = new Weekend<>(OutStoreForm.class);
        //WeekendCriteria<SbCheckForm, Object> weekendCriteria = weekend.weekendCriteria();
        //weekendCriteria.andIn(SbCheckForm::getId, ids);
        //mapper.deleteByExample(weekend);
        ids.forEach(id -> {
            cascadingDeleteByKey(id);
        });
        return 1;
    }

    @Override
    public AbstractPageResultBean<SbCheckFormVO> selectPageList(SbCheckFormDTO model, int pageNum, int pageSize) {
        if (model.getFilter() != null && DataFilterTypeEnum.SELF.getValue() == model.getFilter().intValue()) {
            UserInfo userInfo = SecurityUtils.getUserInfo();
            model.setCreatedUserId(userInfo.getUserId());
        }
        PageHelper.startPage(pageNum, pageSize);
        return new MyPage(mapper.selectList(model));
    }

    @Override
    public SbCheckFormVO getDetail(Object id) {
        SbCheckForm inStoreForm = mapper.selectByPrimaryKey(id);
        SbCheckFormVO inStoreFormVO = new SbCheckFormVO();
        BeanConverterUtil.copyObjectProperties(inStoreForm, inStoreFormVO);
        // 查询验收详情列表
        inStoreFormVO.setDetailList(mapper.selectDetailList(id));
        return inStoreFormVO;
    }

    /**
     * 只有未验收状态才可以删除，不需要回滚
     *
     * @param id ：
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cascadingDeleteByKey(String id) {
        SbCheckForm form = mapper.selectByPrimaryKey(id);
        if (form.getStatus() != null && (form.getStatus().intValue() == SbCheckStatusEnum.EXECUTING.getValue())) {
            throw new BusinessException("已验收的不可以删除，验收单id：" + form.getId());
        }
        // 刪除验收单
        int result = mapper.deleteByPrimaryKey(id);
        UserInfo userInfo = SecurityUtils.getUserInfo();
        // 刪除详情，更新详情涉及的库存
        if (result == 1) {
            Weekend<SbCheckDetail> detailWeekend = new Weekend<>(SbCheckDetail.class);
            detailWeekend.weekendCriteria().andEqualTo(SbCheckDetail::getCheckId, id);
            List<SbCheckDetail> detailList = detailMapper.selectByExample(detailWeekend);

            // 批量删除验收详情
            List<String> ids = detailList.stream().map(SbCheckDetail::getId).collect(Collectors.toList());
            Weekend<SbCheckDetail> weekend = new Weekend<>(SbCheckDetail.class);
            WeekendCriteria<SbCheckDetail, Object> weekendCriteria = weekend.weekendCriteria();
            weekendCriteria.andIn(SbCheckDetail::getId, ids);
            int deleteNum = detailMapper.deleteByExample(weekend);
        }
        return true;
    }

    @Override
    public AbstractPageResultBean<SbCheckForm> selectPageInfo(SbCheckFormDTO model, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        if (model.getFilter() != null && DataFilterTypeEnum.SELF.getValue() == model.getFilter().intValue()) {
            UserInfo userInfo = SecurityUtils.getUserInfo();

            List<StoreVO> storeList = storeService.selectListByUserId(userInfo.getUserId());
            List<String> storeIdList = new ArrayList<String>();
            storeList.forEach(storeVO -> {
                storeIdList.add(storeVO.getId());
            });
            model.setStoreIdList(storeIdList);
        }
        return new MyPage(mapper.selectList(model));
    }

    @Override
    public SbCheckForm saveModelByDTO(SbCheckFormDTO model) {
        UserInfo userInfo = SecurityUtils.getUserInfo();
        model.setUserInfo(userInfo);
        Weekend<SbCheckForm> weekend = new Weekend<>(SbCheckForm.class);
        weekend.weekendCriteria().andIsNotNull(SbCheckForm::getId);
        Integer count = mapper.selectCountByExample(weekend);
        model.setNo(IdGeneratorUtils.getSbCheckNo(++count));
        model.setStatus(SbCheckStatusEnum.NOT_EXECUTE.getValue());
        SbCheckForm inStoreForm = super.saveModelByDTO(model);
        // 验收单详情
        List<SbCheckDetailDTO> detailList = model.getDetailList();
        // 插入
        detailList.forEach(detail -> {
            detail.setUserInfo(userInfo);
            detail.setType(inStoreForm.getType());
            detail.setCheckId(inStoreForm.getId());
            detail.setNo(inStoreForm.getNo());
            detail.setStoreId(inStoreForm.getStoreId());
            SbCheckDetail storeDetail = new SbCheckDetail();
            BeanConverterUtil.copyObjectProperties(detail, storeDetail);
            SbCheckDetail result = detailMapper.selectByPrimaryKey(detail.getId());
            if (ObjectUtil.isNull(result)) {
                detail.setId(IdGeneratorUtils.getObjectId());
                detailMapper.insertSelective(storeDetail);
            } else {
                storeDetail.setUpdateTime(LocalDateTime.now());
                storeDetail.setUpdateUserId(userInfo.getUserId());
                detailMapper.updateByPrimaryKeySelective(storeDetail);
            }

        });
        return inStoreForm;
    }

    @Override
    public void updateModelByDTO(SbCheckFormDTO model) {
        // 更新
        super.modModelByDTO(model);
        // 验收单详情
        UserInfo userInfo = SecurityUtils.getUserInfo();
        List<SbCheckDetailDTO> detailList = model.getDetailList();
        // 先删后插,前端删除的不存在与ids里面，说明被删掉了，需要删除
        Weekend<SbCheckDetail> detailWeekend = new Weekend<>(SbCheckDetail.class);
        List<String> ids = detailList.stream().map(SbCheckDetailDTO::getId).collect(Collectors.toList());
        detailWeekend.weekendCriteria().andNotIn(SbCheckDetail::getId, ids).andEqualTo(SbCheckDetail::getCheckId, model.getId());
        List<SbCheckDetail> delDetailList = detailMapper.selectByExample(detailWeekend);
        detailMapper.deleteByExample(detailWeekend);

        // 新增
        detailList.forEach(detail -> {
            SbCheckDetail realDetail = detailMapper.selectByPrimaryKey(detail.getId());
            if (ObjectUtil.isNull(realDetail)) {// 新增的
                detail.setUserInfo(userInfo);
                detail.setCheckId(model.getId());
                detail.setStoreId(model.getStoreId());
                detail.setNo(model.getNo());
                SbCheckDetail storeDetail = new SbCheckDetail();
                BeanConverterUtil.copyObjectProperties(detail, storeDetail);
                storeDetail.setId(IdGeneratorUtils.getObjectId());
                detailMapper.insertSelective(storeDetail);
            }
        });

    }

    /**
     * 采购单生成验收单和验收明细
     *
     * @param dto
     * @param purchaseList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SbCheckForm saveModelByPurchase(PurchaseOrder dto, List<PurchaseList> purchaseList) {

        UserInfo userInfo = SecurityUtils.getUserInfo();

        SbCheckFormDTO model = new SbCheckFormDTO();
        Weekend<SbCheckForm> weekend = new Weekend<>(SbCheckForm.class);
        weekend.weekendCriteria().andIsNotNull(SbCheckForm::getId);
        Integer count = mapper.selectCountByExample(weekend);
        model.setUserInfo(userInfo);
        model.setNo(IdGeneratorUtils.getSbCheckNo(++count));
        model.setCreatedUserId(dto.getCreatedUserId());
        model.setType(SbCheckTypeEnum.CAIGOU.getValue());
        // 根据采购类型，设置验收类型，验收后才能验收，验收的同时，修改数量
        model.setGoodType(dto.getType());
        model.setCreatedTime(dto.getCreatedTime());
        model.setDemandPlanId(dto.getDemandPlanId());
        model.setPurchaseId(dto.getId());
        model.setPurchaseNo(dto.getBillNo());
        model.setPurchasePlanId(dto.getPurchasePlanId());
        model.setTotalPrice(dto.getAccountTotalMoney());
        // 仓库负责人
        Store store = storeService.getModelById(dto.getWarehouseId());
        if (store == null) {
            throw new BusinessException("找不到仓库，请给项目部设置总仓以及对应的负责人, storeId:" + dto.getWarehouseId());
        }
        if (store.getUserId() == null) {
            throw new BusinessException("找不到仓库的负责人，请设置负责人, storeId:" + store.getId());
        }
        model.setStoreId(dto.getWarehouseId());
        model.setCheckUserId(store.getUserId());
        model.setStatus(SbCheckStatusEnum.NOT_EXECUTE.getValue());
        SbCheckForm inStoreForm = super.saveModelByDTO(model);

        List<SpareStoreDTO> storeDTOS = new ArrayList<>();
        // 保存验收明细
        List<SbCheckDetail> detailList = new ArrayList<SbCheckDetail>();
        purchaseList.forEach(dispatchOrder -> {
            SbCheckDetail detail = new SbCheckDetail();
            detail.setId(IdGeneratorUtils.getObjectId());
            detail.setCreatedTime(dispatchOrder.getCreatedTime());
            detail.setCreatedUserId(dispatchOrder.getCreatedUserId());
            detail.setCheckId(inStoreForm.getId());
            detail.setName(dispatchOrder.getName());
            detail.setStoreId(inStoreForm.getStoreId());
            detail.setPurchaseDetailId(dispatchOrder.getId());
            detail.setModelId(dispatchOrder.getGoodsId());// 这个是设备型号id吧？
            detail.setNo(inStoreForm.getNo());
            detail.setNum(dispatchOrder.getQuantity());
            detail.setPrice(dispatchOrder.getAccountPrice());
            detail.setTotalPrice(dispatchOrder.getAccountTotalMoney());
            detail.setPurchaseNum(dispatchOrder.getQuantity());
            detail.setPurchasePrice(dispatchOrder.getAccountPrice());
            detail.setPurchaseTotalPrice(dispatchOrder.getAccountTotalMoney());
            detailList.add(detail);

            SpareStoreDTO storeDTO = new SpareStoreDTO();
            storeDTO.setStoreId(dto.getWarehouseId());
            storeDTO.setSpareId(dispatchOrder.getGoodsId());
            storeDTO.setGgxh(dispatchOrder.getSpecs());
            storeDTO.setPrice(dispatchOrder.getAccountPrice());
            storeDTO.setTypeId(dispatchOrder.getType());
            storeDTOS.add(storeDTO);
        });
        if (!CollectionUtils.isEmpty(detailList)) {
            detailMapper.insertListforComplex(detailList);
        }
        if (!CollectionUtils.isEmpty(storeDTOS)) {
            storeDTOS.forEach(item -> {
                spareStoreService.saveModelByDTO(item);
            });
        }
        return inStoreForm;
    }

    /**
     * 发运单生成验收单
     *
     * @param dto
     * @param dispatchOrderList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SbCheckForm saveModelByPurchaseDispatchOrder(PurchaseDispatchOrder dto, List<PurchaseDispatchOrderList> dispatchOrderList) {
        UserInfo userInfo = SecurityUtils.getUserInfo();

        SbCheckFormDTO model = new SbCheckFormDTO();
        Weekend<SbCheckForm> weekend = new Weekend<>(SbCheckForm.class);
        weekend.weekendCriteria().andIsNotNull(SbCheckForm::getId);
        Integer count = mapper.selectCountByExample(weekend);
        model.setNo(IdGeneratorUtils.getSbCheckNo(++count));
        model.setType(SbCheckTypeEnum.FAYUN.getValue());
        model.setGoodType(dto.getType());
        model.setCreatedUserId(dto.getCreatedUserId());
        model.setCreatedTime(dto.getCreatedTime());
        model.setDemandPlanId(dto.getDemandPlanId());
        model.setPurchaseDispatchOrderId(dto.getId());
        model.setPurchaseId(dto.getPurchaseOrderId());
        model.setPurchaseNo(dto.getBillNo());
        model.setPurchasePlanId(dto.getPurchasePlanId());
        model.setTotalPrice(dto.getAccountTotalMoney());
        Store store = storeService.getModelById(dto.getWarehouseId());
        if (store == null) {
            throw new BusinessException("找不到仓库，请给项目部设置总仓以及对应的负责人, storeId:" + dto.getWarehouseId());
        }
        if (store.getUserId() == null) {
            throw new BusinessException("找不到仓库的负责人，请设置负责人, storeId:" + store.getId());
        }
        model.setStoreId(dto.getWarehouseId());
        model.setCheckUserId(store.getUserId());
        model.setStatus(SbCheckStatusEnum.NOT_EXECUTE.getValue());
        SbCheckForm inStoreForm = super.saveModelByDTO(model);

        // 明细
        List<SbCheckDetail> detailList = new ArrayList<SbCheckDetail>();
        List<SpareStoreDTO> storeDTOS = new ArrayList<>();
        dispatchOrderList.forEach(dispatchOrder -> {
            SbCheckDetail detail = new SbCheckDetail();
            detail.setCreatedTime(dispatchOrder.getCreatedTime());
            detail.setCreatedUserId(dispatchOrder.getCreatedUserId());
            detail.setCheckId(inStoreForm.getId());
            detail.setPurchaseDetailId(dispatchOrder.getId());
            detail.setId(IdGeneratorUtils.getObjectId());
            detail.setStoreId(inStoreForm.getStoreId());
            detail.setModelId(dispatchOrder.getGoodsId());
            detail.setName(dispatchOrder.getName());
            detail.setNo(inStoreForm.getNo());
            detail.setNum(dispatchOrder.getQuantity());
            detail.setPrice(dispatchOrder.getAccountPrice());
            detail.setTotalPrice(dispatchOrder.getAccountTotalMoney());
            detail.setPurchaseNum(dispatchOrder.getQuantity());
            detail.setPurchasePrice(dispatchOrder.getAccountPrice());
            detail.setPurchaseTotalPrice(dispatchOrder.getAccountTotalMoney());
            detailList.add(detail);

            SpareStoreDTO storeDTO = new SpareStoreDTO();
            storeDTO.setStoreId(dto.getWarehouseId());
            storeDTO.setSpareId(dispatchOrder.getGoodsId());
            storeDTO.setGgxh(dispatchOrder.getSpecs());
            storeDTO.setPrice(dispatchOrder.getAccountPrice());
            storeDTO.setTypeId(dispatchOrder.getType());
            storeDTOS.add(storeDTO);
        });
        if (!CollectionUtils.isEmpty(detailList)) {
            detailMapper.insertListforComplex(detailList);
        }
        if (!CollectionUtils.isEmpty(storeDTOS)) {
            storeDTOS.forEach(item -> {
                spareStoreService.saveModelByDTO(item);
            });
        }
        return inStoreForm;
    }

    /**
     * 提交验收单,如果设备采购，则生成设备基础信息
     * 如果是其他的，则生成验收单
     * <p>
     * 回写发运单或者采购单的数量
     *
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void checkIn(String id) {
        SbCheckForm model = this.getModelById(id);
        model.setStatus(SbCheckStatusEnum.EXECUTING.getValue());
        mapper.updateByPrimaryKey(model);

        // 找到明细
        Weekend<SbCheckDetail> detailWeekend = new Weekend<>(SbCheckDetail.class);
        detailWeekend.weekendCriteria().andEqualTo(SbCheckDetail::getCheckId, model.getId());
        List<SbCheckDetail> detailList = detailMapper.selectByExample(detailWeekend);
        if (model.getGoodType() <= PurchaseTypeEnum.PURCHASE_APPLY_TYPE_SB.getValue()) {
            this.addSbInfo(model, detailList);
        } else {
            inStoreFormService.saveModelBySbCheckForm(model, detailList);
        }

        this.updatePurchase(model, detailList);
    }

    /**
     * 生成设备基础信息，由设备主管进行调拨，初始化为在库状态，且没有编号，自行填写编号并修改状态
     * 设备先挂靠到设备主管头上，由主管跟踪进行调拨给其他人员使用
     *
     * @param dto
     * @param detailList
     */
    public void addSbInfo(SbCheckForm dto, List<SbCheckDetail> detailList) {

        Store store = storeService.getModelById(dto.getStoreId());
        UserInfo userInfo = SecurityUtils.getUserInfo();

        // 获取部门的项目部
        SysDeptVO natureDept = UserUtil.getUserNatureDept(DeptNatureEnum.XIANG_MU_BU, userInfo);
        // 获取项目部设备主管
        List<SysUserVO> users = UserUtil.selectUserByIdentityTypeLikeDeptCode(natureDept.getDeptCode(),
                SysUserIdentityType.WXZG.getValue());
        SysUserVO checkUser = null;
        if (CollectionUtil.isNotEmpty(users)) {
            checkUser = users.get(0);
        }

        if(checkUser == null){
            throw new BusinessException("找不到该项目部的维修主管，项目部名称："+natureDept.getName());
        }

        // 生成设备信息
        List<SbInfo> infoList = new ArrayList<SbInfo>();
        for (SbCheckDetail detail : detailList) {
            SbModel sbModel = sbModelMapper.selectByPrimaryKey(detail.getModelId());
            for (int i = 0; i < detail.getNum().intValue(); i++) {
                SbInfoDTO info = new SbInfoDTO();
                info.setUserInfo(userInfo);
                info.setCheckId(dto.getId());
                info.setModelId(detail.getModelId());
                info.setName(sbModel.getName());
                info.setLevel(sbModel.getLevel());
                info.setTypeId(sbModel.getTypeId());
                info.setUseType(sbModel.getUseType());
                info.setInitialValue(new BigDecimal(sbModel.getValue()));
                info.setProducerId(sbModel.getProducerId());
                info.setUnit(sbModel.getUnit());
                info.setBuyDate(LocalDate.now());
                info.setStartDate(LocalDate.now());
                info.setUseCompany(store.getUseCompany());
                info.setUseProject(store.getUseProject());
                info.setSaveUser(checkUser.getUserId());
                info.setUseUser(checkUser.getUserId());
                SysDeptDTO sysDeptDTO = new SysDeptDTO();
                sysDeptDTO.setDescendant(store.getUseCompany());
                sysDeptDTO.setNature(DeptNatureEnum.JITUAN.getValue());
                List<SysDeptVO> list = sysDeptService.allParentList(sysDeptDTO);
                if (CollectionUtil.isEmpty(list)) {
                    throw new BusinessException("找不到该用户所属的公司，请先设置，用户id:" + userInfo.getUserId());
                }
                info.setUseArea(list.get(0).getDeptId());
                info.setStatus(SbInfoStatusEnum.IN_STORE.getValue());
                infoList.add(sbInfoService.saveModelByDTO(info));
            }
        }



        List<String> nos = infoList.stream().map(SbInfo::getNo).collect(Collectors.toList());

        // 通知设备主管进行设备调拨
        SpringContextHolder.publishEvent(new WorkplaceBacklogEvent( WorkplaceBacklogTypeEnum.PURCHASE_SB_MESSAGE.getValue(), WorkplaceBacklogDetailTypeEnum.PURCHASE_SB_MESSAGE.getValue(),
                dto.getId(), MessageTemplateUtil.getPurchaseSbCheck(nos),
                dto.getId(), ListUtils.newArrayList(checkUser.getUserId())));

    }


    /**
     * 回写采购信息
     *
     * @param model
     * @param detailList
     */
    public void updatePurchase(SbCheckForm model, List<SbCheckDetail> detailList) {
        // 验收单详情
        UserInfo userInfo = SecurityUtils.getUserInfo();

        // 回写采购单和明细or发运单信息和明细
        PurchaseOrder purchaseOrder = null;
        List<PurchaseList> purchaseOrderList = new ArrayList<PurchaseList>();
        PurchaseDispatchOrder purchaseDispatchOrder = null;
        List<PurchaseDispatchOrderList> purchaseDispatchOrderList = new ArrayList<PurchaseDispatchOrderList>();

        for (SbCheckDetail detail : detailList) {
            // 回写采购单和明细or发运单信息和明细
            if (model.getType().equals(SbCheckTypeEnum.CAIGOU.getValue())) {
                PurchaseList purchaseList = purchaseListMapper.selectByPrimaryKey(detail.getPurchaseDetailId());
                purchaseList.setArrivedQuantity(detail.getNum());
                purchaseOrderList.add(purchaseList);
            } else if (model.getType().equals(SbCheckTypeEnum.FAYUN.getValue())) {
                PurchaseDispatchOrderList dispatchList = purchaseDispatchOrderListMapper.selectByPrimaryKey(detail.getPurchaseDetailId());
                dispatchList.setArrivedQuantity(detail.getNum());
                purchaseDispatchOrderList.add(dispatchList);
            }
        }
        ;

        if (model.getType().equals(SbCheckTypeEnum.CAIGOU.getValue())) {
            purchaseOrder = purchaseOrderMapper.selectByPrimaryKey(model.getPurchaseId());
            if (CollectionUtil.isNotEmpty(purchaseOrderList)) {
                purchaseBusinessService.updateOrderListArrivedQuantity(purchaseOrder, purchaseOrderList);
            }
        } else if (model.getType().equals(SbCheckTypeEnum.FAYUN.getValue())) {
            purchaseDispatchOrder = purchaseDispatchOrderMapper.selectByPrimaryKey(model.getPurchaseDispatchOrderId());
            if (CollectionUtil.isNotEmpty(purchaseDispatchOrderList)) {
                purchaseBusinessService.updateOrderListArrivedQuantity(purchaseDispatchOrder, purchaseDispatchOrderList);
            }
        }
    }
}
